import React from "react";
import {useSelector} from "react-redux";
import {RootState} from "@/stores";
import {usePathname} from "next/navigation";
import {findAllMenuItemByPath} from "../../config/menu";
import Access_Enum from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";
import Forbidden from "@/app/forbidden";

/**
 * 统一权限校验拦截器
 * @param children
 * @constructor
 */
const AccessLayout: React.FC<Readonly<{ children: React.ReactNode }>> = ({children}) => {
    const pathname = usePathname()
    // 当前登录用户
    const loginUser = useSelector((state: RootState) => state.loginUser);
    // 根据路径获取菜单
    const menu = findAllMenuItemByPath(pathname) || {};
    // 需要的权限
    const needAccess = menu?.access ?? Access_Enum.NOT_LOGIN;
    // 判断是否拥有权限
    const canAccess = checkAccess(loginUser, needAccess);
    if (!canAccess) {
        return <Forbidden />
    }
    return <>{children}</>
};

export default AccessLayout;